//
//  JDClassificationViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/10/27.
//

import UIKit

class JDClassificationViewController: JDBaseViewController {

    var leftTableView: UITableView?
    var rightCollectionView: UICollectionView?
    
    var leftDataSource: [String]?
    var leftSelectedIndex = 0
    var rightDataSource: [String]?
    var rightSelectedIndex = 0
    
    let subWidth = (screenWidth-40-1)/4.0
    
    var goodsTypeModels :[JDGoodsTypeModel?]?
    
    
    var selectedClassificationCompleted: ((Int, String?)->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupNavigationTitle("分类")
        self.setupLeftBackItem()
        self.leftDataSource = [String]()
        self.rightDataSource = [String]()
        
        for item in self.goodsTypeModels ?? [JDGoodsTypeModel?]() {
            if let leftName = item?.name {
                self.leftDataSource?.append(leftName)
            }
        }
        
        for item in self.goodsTypeModels?.first??.children ?? [JDGoodsSecondTypeModel]() {
            if let rightName = item.name {
                self.rightDataSource?.append(rightName)
            }
        }
        
//        self.rightDataSource = ["右1","右2","右3","右4","右5","右6"]
        
    }
    
    func setupUIElements() {
        
        self.leftTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.leftTableView!)
        self.leftTableView?.snp.makeConstraints({ make in
            make.leading.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.view)
            make.width.equalTo(self.subWidth)
            
        })
        self.leftTableView?.delegate = self
        self.leftTableView?.dataSource = self
        self.leftTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "leftCell")
        self.leftTableView?.separatorStyle = .none
        self.leftTableView?.bounces = false
        self.leftTableView?.backgroundColor = .commonColor()

        let layout = UICollectionViewFlowLayout()
        
        self.rightCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        self.view.addSubview(self.rightCollectionView!)
        self.rightCollectionView?.snp.makeConstraints({ make in
            make.trailing.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.view)
            make.leading.equalTo(self.leftTableView!.snp.trailing)
        })
        self.rightCollectionView?.delegate = self
        self.rightCollectionView?.dataSource = self
        self.rightCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "rightCell")
        self.rightCollectionView?.backgroundColor = .white
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDClassificationViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.leftDataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "leftCell")
        
        cell?.selectionStyle = .none
        
        let str = self.leftDataSource?[indexPath.row]
        
        let contentLabel = UILabel()
        cell?.contentView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.leading.trailing.equalTo(cell!.contentView)
            make.top.bottom.equalTo(cell!.contentView)
        }
        contentLabel.textAlignment = .center
        contentLabel.text = str
        
        let leftLine = UIView()
        cell?.contentView.addSubview(leftLine)
        leftLine.snp.makeConstraints { make in
            make.centerY.equalTo(contentLabel)
            make.size.equalTo(CGSize(width: 2, height: 22))
        }
        leftLine.backgroundColor = color("#FA6161")
        
        if indexPath.row == self.leftSelectedIndex {
            contentLabel.backgroundColor = .white
            contentLabel.textColor = color("#FA6161")
            contentLabel.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
            leftLine.isHidden = false
        } else {
            contentLabel.backgroundColor = .commonColor()
            contentLabel.textColor = color("#333333")
            contentLabel.font = UIFont.systemFont(ofSize: 16, weight: .regular)
            leftLine.isHidden = true
        }
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 58
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.goodsTypeModels?[indexPath.row]
        self.leftSelectedIndex = indexPath.row
        self.rightDataSource?.removeAll()
        for item in model?.children ?? [JDGoodsSecondTypeModel]() {
            if let rightName = item.name {
                self.rightDataSource?.append(rightName)
            }
        }
        
//        self.rightDataSource = ["右1","右2","右3","右4","右5","右6"]
        
        self.leftTableView?.reloadData()
        self.rightCollectionView?.reloadData()
    }
    
}

extension JDClassificationViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.rightDataSource?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "rightCell", for: indexPath)
        
        for subV in cell.contentView.subviews {
            subV.removeFromSuperview()
        }        
        
        let str = self.rightDataSource?[indexPath.row]
        
        let contentLabel = UILabel()
        cell.contentView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { make in
            make.leading.trailing.equalTo(cell.contentView)
            make.top.bottom.equalTo(cell.contentView)
        }
        contentLabel.makeCorner(4)
        let (bgColor,textColor) = UIColor.customRandomColor()
        contentLabel.backgroundColor = bgColor
        
        contentLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: textColor, numberOfLines: 1)
        
        contentLabel.text = str
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.subWidth, height: 57)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 11, left: 12, bottom: 11, right: 12)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        guard let leftModel = self.goodsTypeModels?[self.leftSelectedIndex] else { return }
        
        guard let selectedModel = leftModel.children?[indexPath.row] else { return }
        
        self.selectedClassificationCompleted?(self.leftSelectedIndex, selectedModel.id)
        
        self.navigationController?.popViewController(animated: true)
    }
    
}
